package com.example.diethealthsystem.controller;

import com.example.diethealthsystem.entity.User;
import com.example.diethealthsystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Optional;

@Controller
public class ProfileController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/profile")
    public String showProfilePage(Model model) {
        model.addAttribute("users", userRepository.findAll());
        return "profile/index";
    }

    // 新增用户
    @PostMapping("/users/add")
    public String addUser(@RequestParam String displayName,
                          @RequestParam String username,
                          @RequestParam String email,
                          @RequestParam String role,
                          @RequestParam String password,
                          RedirectAttributes redirectAttributes) {
        try {
            // 检查用户名是否已存在
            if (userRepository.findByUsername(username) != null) {
                redirectAttributes.addFlashAttribute("error", "用户名已存在！");
                return "redirect:/profile";
            }

            User user = new User();
            user.setDisplayName(displayName);
            user.setUsername(username);
            user.setEmail(email);
            user.setRole(role);
            user.setPassword(password); // 注意：实际应用中应该对密码进行加密
            user.setRegisteredAt(java.time.LocalDateTime.now());
            user.setBanned(false);
            
            userRepository.save(user);
            redirectAttributes.addFlashAttribute("success", "新增用户成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "新增用户失败：" + e.getMessage());
        }
        return "redirect:/profile";
    }

    // 编辑用户
    @PostMapping("/users/edit")
    public String editUser(@RequestParam Long id,
                           @RequestParam String displayName,
                           @RequestParam String username,
                           @RequestParam String email,
                           @RequestParam String role,
                           RedirectAttributes redirectAttributes) {
        try {
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            // 检查新用户名是否与其他用户重复
            Optional<User> existingUser = userRepository.findByUsername(username);
            if (existingUser.isPresent() && !existingUser.get().getId().equals(id)) {
                redirectAttributes.addFlashAttribute("error", "用户名已存在！");
                return "redirect:/profile";
            }

            user.setDisplayName(displayName);
            user.setUsername(username);
            user.setEmail(email);
            user.setRole(role);
            
            userRepository.save(user);
            redirectAttributes.addFlashAttribute("success", "用户信息修改成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "修改用户信息失败：" + e.getMessage());
        }
        return "redirect:/profile";
    }

    // 删除用户
    @PostMapping("/users/delete")
    public String deleteUser(@RequestParam Long id, RedirectAttributes redirectAttributes) {
        try {
            if (!userRepository.existsById(id)) {
                redirectAttributes.addFlashAttribute("error", "用户不存在！");
                return "redirect:/profile";
            }
            
            userRepository.deleteById(id);
            redirectAttributes.addFlashAttribute("success", "用户删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除用户失败：" + e.getMessage());
        }
        return "redirect:/profile";
    }
}